import {Fence} from "./fence";
import {Matrix} from "./Matrix";

class FenceGroup {

    spu
    skuList = []
    fences = []

    constructor(spu) {
        this.spu = spu
        this.skuList = spu.sku_list
    }

    getDefaultSku() {
        const defaultSkuId = this.spu.default_sku_id
        if (!defaultSkuId) return
        return this.skuList.find(e => e.id === defaultSkuId)
    }

    getSku(code) {
        // const sku = this.spu.sku_list.find(s => s.code === code)
        // return sku ? sku : null
        const skuCode = this.spu.id+'$'+code
        return this.spu.sku_list.find(s => s.code === skuCode) || null
    }

    setCellStatusById(cellId, status) {
        this.eachCell((cell, x, y) => {
            if (cell.id === cellId)
                cell.status = status
        })
    }

    setCellStatusByXY(x, y, status) {
        this.fences[x].cells[y].status = status
    }

    initFences() {
        // matrix是二维数组[[spec1],[spec2],[spec3]]
        const matrix = this.createMatrix(this.skuList)
        const fences = []
        const AT = matrix.transpose()
        AT.forEach(at => {
            const fence = new Fence(at)
            fence.init()
            if (this._hasSketchFence && this._isSketchFence(fence.id)){
                fence.setSketchFence(this.skuList)
            }
            fences.push(fence)
        })
        this.fences = fences
    }

    _hasSketchFence() {
        return this.spu.sketch_spec_id
    }

    _isSketchFence(fenceId) {
        return this.spu.sketch_spec_id === fenceId
    }

    // 矩阵转置
    createMatrix(sku_list) {
        const m = []
        sku_list.forEach(sku => {
            m.push(sku.specs)
        })
        return new Matrix(m)
    }

    // 遍历每一行每一列的cell
    eachCell(callback) {
        for (let x = 0; x < this.fences.length; x++) {
            for (let y = 0; y < this.fences[x].cells.length; y++) {
                const cell = this.fences[x].cells[y]
                callback(cell, x, y)
            }
        }
    }
}

export {
    FenceGroup
}
